package com.hue.gulimailcart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hue.common.constant.CartConstant;
import com.hue.common.to.UserInfoTo;
import com.hue.common.utils.R;
import com.hue.gulimailcart.feign.ProductFeignService;
import com.hue.gulimailcart.interceptor.LoginStatusInterceptor;
import com.hue.gulimailcart.service.CartService;
import com.hue.gulimailcart.vo.Cart;
import com.hue.gulimailcart.vo.CartItem;
import com.hue.gulimailcart.vo.SkuInfoVo;
import com.hue.gulimailcart.vo.SkuSaleAttrValueVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/15 21:31
 * @Description:
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItem addToCart(Long skuId, Integer count) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //判断购物车有没有这个商品，没有就添加，有就修改数量
        String res = (String) cartOps.get(skuId.toString());
        if (!StringUtils.isEmpty(res)) {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + count);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

        //购物车没有这个商品
        CartItem cartItem = new CartItem();

        //调用商品服务查询skuInfo
        CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
            R r = productFeignService.getSkuInfo(skuId);
            if ((Integer) r.get("code") == 0) {
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setSkuId(skuId);
                cartItem.setCount(count);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
            }
        }, threadPoolExecutor);

        //调用商品服务获取sku的销售属性
        CompletableFuture<Void> skuSaleFuture = CompletableFuture.runAsync(() -> {
            R r = productFeignService.getBySkuId(skuId);
            if ((Integer) r.get("code") == 0) {
                List<SkuSaleAttrValueVo> attrValues = r.getData("attrValues", new TypeReference<List<SkuSaleAttrValueVo>>() {
                });
                List<String> values = attrValues.stream().map((attrValue) -> attrValue.getAttrName() + ":" + attrValue.getAttrValue()).collect(Collectors.toList());
                cartItem.setSkuAttr(values);
            }
        }, threadPoolExecutor);

        //等待两个异步任务执行完成
        CompletableFuture.allOf(skuInfoFuture, skuSaleFuture).get();

        //将商品添加到购物车
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

        return cartItem;
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();

        UserInfoTo userInfoTo = LoginStatusInterceptor.threadLocal.get();

        //获取离线购物车数据
        List<CartItem> offlineCartItems = getOfflineCart(userInfoTo);

        if (userInfoTo.getUserId() != null) {
            //已经登录,将离线购合并到当前用户的购物车中
            BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX + userInfoTo.getUserId());
            List<Object> loginCartItemObj = cartOps.values();

            if (loginCartItemObj != null && loginCartItemObj.size() > 0) {
                List<CartItem> loginCartItems = loginCartItemObj.stream()
                        .map((obj) -> JSON.parseObject((String) obj, CartItem.class))
                        .collect(Collectors.toList());

                //将两个购物车的数据合并
                List<CartItem> cartItems = mergerCart(offlineCartItems, loginCartItems);

                //更新用户购物车数据
                if (cartItems != null) {
                    for (CartItem cartItem : cartItems) {
                        cartOps.put(cartItem.getSkuId().toString(), JSON.toJSONString(cartItem));
                    }
                }

                //清空离线购物车
                clearOfflineCart(userInfoTo);

                cart.setCartItems(cartItems);
                return cart;
            }
        }

        cart.setCartItems(offlineCartItems);
        return cart;
    }

    @Override
    public CartItem getCartItemBySkuId(Long skuId) {
        String jsonString = (String) getCartOps().get(skuId.toString());

        if (!StringUtils.isEmpty(jsonString)) {
            return JSON.parseObject(jsonString, CartItem.class);
        }

        return new CartItem();
    }

    @Override
    public void checkedItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String jsonStr = (String) cartOps.get(skuId.toString());

        CartItem cartItem = JSON.parseObject(jsonStr, CartItem.class);
        cartItem.setCheck(check == 1);

        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    /**
     * 获取当前用户需要操作的购物车
     *
     * @return
     */
    public BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = LoginStatusInterceptor.threadLocal.get();
        String userKey;
        if (userInfoTo.getUserId() != null) {
            userKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            userKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(userKey);
        return cartOps;
    }

    /**
     * 获取当前离线用户的购物车
     *
     * @return
     */
    public List<CartItem> getOfflineCart(UserInfoTo userInfoTo) {
        //没有登录,获取购物车的信息
        BoundHashOperations<String, Object, Object> cartOps =
                redisTemplate.boundHashOps(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
        List<Object> cartItemsObj = cartOps.values();

        if (cartItemsObj != null && !cartItemsObj.isEmpty()) {
            List<CartItem> cartItems = cartItemsObj.stream()
                    .map((obj) -> JSON.parseObject((String) obj, CartItem.class))
                    .collect(Collectors.toList());

            return cartItems;
        }

        return null;
    }

    /**
     * 合并两个购物车
     *
     * @param offlineCartItems
     * @param loginCartItems
     * @return
     */
    public List<CartItem> mergerCart(List<CartItem> offlineCartItems, List<CartItem> loginCartItems) {
        Map<Long, CartItem> loginCartItemsMap = loginCartItems.stream()
                .collect(Collectors.toMap(CartItem::getSkuId, cartItem -> cartItem));

        if (offlineCartItems != null && offlineCartItems.size() > 0) {
            for (CartItem cartItem : offlineCartItems) {
                if (loginCartItemsMap.containsKey(cartItem.getSkuId())) {
                    CartItem item = loginCartItemsMap.get(cartItem.getSkuId());
                    item.setCount(item.getCount() + cartItem.getCount());
                } else {
                    loginCartItemsMap.put(cartItem.getSkuId(), cartItem);
                }
            }
        }

        return loginCartItemsMap.values().stream().collect(Collectors.toList());
    }

    /**
     * 清空离线购物车
     *
     * @param userInfoTo
     */
    public void clearOfflineCart(UserInfoTo userInfoTo) {
        redisTemplate.delete(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
    }
}
